package com.estronger.shopmanage.ui.home;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.utils.DownLoadFileUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

import cn.jesse.nativelogger.NLogger;

/**
 * 经验分享的详细界面
 *
 * @author Administrator
 */
public class WebActivity extends BaseActivity {

    private TextView titleView, txtHint;
    private WebView webView;
    private String title, url;

    @Override
    protected void init() {
        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        try {
            //url = URLEncoder.encode(intent.getStringExtra("url"), "UTF-8");
            url = intent.getStringExtra("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView() {
        /*
         * 初始化布局
         */
        setContentView(R.layout.activity_web);
        titleView = (TextView) findViewById(R.id.web_title);
        webView = (WebView) findViewById(R.id.webView);
        txtHint = (TextView) findViewById(R.id.txtHint);
        txtHint.setOnClickListener(null);
        titleView.setText(title);
        // 根据url加载webView
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                NLogger.w(url + "\n" + userAgent + "\n" + contentDisposition + "\n" + mimeType + "\n" + contentLength);
                txtHint.setVisibility(View.VISIBLE);

                if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    Toast t = Toast.makeText(WebActivity.this, "需要SD卡。", Toast.LENGTH_LONG);
                    t.setGravity(Gravity.CENTER, 0, 0);
                    t.show();
                    return;
                }
                downLoad();
            }
        });
        webView.getSettings().setJavaScriptEnabled(true);//启用js
        webView.getSettings().setBlockNetworkImage(false);//解决图片不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.loadUrl(url);
    }

    private void downLoad() {
        String fileName = url.substring(url.lastIndexOf("\\") + 1);
        fileName = URLDecoder.decode(fileName);
        final String path2 = "/download/" + fileName;
        File directory = Environment.getExternalStorageDirectory();
        File file = new File(directory, path2);
        if (file.exists()) {
            showHintText(fileName);
        } else {
            HttpUtils httpUtils = new HttpUtils();
            httpUtils.configTimeout(15 * 1000).configSoTimeout(15 * 1000).configRequestRetryCount(3);
            httpUtils.configDefaultHttpCacheExpiry(0);
            final String finalFileName = fileName;
            httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<byte[]>() {
                @Override
                public void onStart() {
                    super.onStart();
                    showProgressDialog();
                }

                @Override
                public void onSuccess(ResponseInfo<byte[]> responseInfo) {
                    try {
                        InputStream inputStream = new ByteArrayInputStream(responseInfo.result);
                        writeToSDCard(path2, inputStream);
                        inputStream.close();
                    } catch (Exception e) {
                    }
                    closeProgressDialog();
                    showHintText(finalFileName);
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    closeProgressDialog();
                    Toast t = Toast.makeText(WebActivity.this, "连接错误！请稍后再试！", Toast.LENGTH_LONG);
                    t.setGravity(Gravity.CENTER, 0, 0);
                    t.show();
                }
            });
        }
    }
    private void showHintText(String fileName){
        if (fileName == null) {
            Toast t = Toast.makeText(WebActivity.this, "连接错误！请稍后再试！", Toast.LENGTH_LONG);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();
            return;
        }

        Toast t = Toast.makeText(WebActivity.this, "已保存到SD卡。", Toast.LENGTH_LONG);
        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();
        File directory = Environment.getExternalStorageDirectory();
        final File file = new File(directory, "/download/" + fileName);
        Log.i("tag", "Path=" + file.getAbsolutePath());

        txtHint.setText("下载完毕\n " + file.getAbsolutePath() + "\n点击打开查看");
        txtHint.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        txtHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(DownLoadFileUtil.openFile(WebActivity.this, file));
            }
        });
    }

    private ProgressDialog mDialog;

    private void showProgressDialog() {
        if (mDialog == null) {
            mDialog = new ProgressDialog(WebActivity.this);
            mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
            mDialog.setMessage("正在加载 ，请等待...");
            mDialog.setIndeterminate(false);//设置进度条是否为不明确
            mDialog.setCancelable(true);//设置进度条是否可以按退回键取消
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    mDialog = null;
                }
            });
            mDialog.show();

        }
    }

    private void closeProgressDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    public Intent getFileIntent(File file) {
//       Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
        Uri uri = Uri.fromFile(file);
        String type = getMIMEType(file);
        Log.i("tag", "type=" + type);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, type);
        return intent;
    }

    public void writeToSDCard(String fileName, InputStream input) {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File directory = Environment.getExternalStorageDirectory();
            File file = new File(directory, fileName);
//          if(file.exists()){
//              Log.i("tag", "The file has already exists.");
//              return;
//          }
            try {
                FileOutputStream fos = new FileOutputStream(file);
                byte[] b = new byte[2048];
                int j = 0;
                while ((j = input.read(b)) != -1) {
                    fos.write(b, 0, j);
                }
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            Log.i("tag", "NO SDCard.");
        }
    }

    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();

        /* 依扩展名的类型决定MimeType */
        if (end.equals("pdf")) {
            type = "application/pdf";//
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        }
//      else if(end.equals("pptx")||end.equals("ppt")){
//        type = "application/vnd.ms-powerpoint";
//      }else if(end.equals("docx")||end.equals("doc")){
//        type = "application/vnd.ms-word";
//      }else if(end.equals("xlsx")||end.equals("xls")){
//        type = "application/vnd.ms-excel";
//      }
        else {
//        /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }

}
